﻿using System;
using System.Collections.Generic;

namespace FrameOperateSync
{
    class OperateLogicManager
    {
        private Queue<KeyValuePair<int, byte[]>> oneFrameOperateQue = new Queue<KeyValuePair<int, byte[]>>(4);
        private List<KeyValuePair<int, FrameOperateData>> _playerKeyOperateList = new List<KeyValuePair<int, FrameOperateData>>(15);
        private int _playerId;

        public event Action<bool, int, FrameOperateData[]> EventFrameOperatesCollect;
        public event Action<bool, int, KeyValuePair<int, FrameOperateData>[]> EventKeyFrameOperatesCollect;
        public int PlayerId => _playerId;

        public OperateLogicManager(int playerId)
        {
            _playerId = playerId;
        }

        public void OperateExcute(int operateCode,IRenderData renderData)
        {
            lock (oneFrameOperateQue)
            {
                oneFrameOperateQue.Enqueue(new KeyValuePair<int, byte[]>(operateCode, RenderData.ToBytes(renderData)));

               // Loger.LogError("数据进去了");
            }
        }

        public void OnFrameTick(int keyFrameIndex, int frameIndex)
        {
            lock (oneFrameOperateQue)
            {
                bool keyFrameFlag = FrameTicker.IsKeyFrameTurn(frameIndex);
                if(keyFrameFlag)
                {
                    if (oneFrameOperateQue.Count == 0)
                    {
                        EventKeyFrameOperatesCollect?.Invoke(false, keyFrameIndex, null);
                    }
                    else
                    {
                        while (oneFrameOperateQue.Count > 0)
                        {
                            var logic = oneFrameOperateQue.Dequeue();             
                            var nodeData = FrameOperateData.Create(_playerId, keyFrameIndex, frameIndex, logic.Key, logic.Value);
                            _playerKeyOperateList.Add(new KeyValuePair<int, FrameOperateData>(frameIndex, nodeData));
                        }
                        EventKeyFrameOperatesCollect?.Invoke(_playerKeyOperateList.Count > 0, keyFrameIndex, _playerKeyOperateList.ToArray());
                    }
                }                
            }
        }
    }
}
